package com.labot.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.labot.Constants;
import com.labot.dao.Dbi18nDao;
import com.labot.dto.I18nDto;
import com.labot.model.I18n;
import com.labot.service.Dbi18nManager;
import com.labot.util.FileUtils;
import com.labot.util.StackTraceUtils;

/**
 * Implementation of UserManager interface.
 * 
 * @author Ing. Enrique Barbeito.
 * 
 */
@Service("i18nManager")
public class Dbi18nManagerImpl extends GenericManagerImpl<I18n, Long> implements Dbi18nManager {

	private Dbi18nDao i18nDao;

	@Autowired
	public void setConfigDao(Dbi18nDao dao) {
		super.dao = dao;
		this.i18nDao = dao;
	}

	@Override
	public List<I18n> getAll() {
		return i18nDao.getAll();
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<I18n> search(String q, Class clazz) {
		return i18nDao.search(q);
	}

	@Override
	public I18n getI18n(String key) {
		return i18nDao.getValue(key);
	}

	@Override
	public List<I18nDto> getJspKeys(String path, Boolean nonExist) {
		// Pages path
		List<I18nDto> result  = new ArrayList<I18nDto>();

		path = path + Constants.FILE_SEP + "pages" + Constants.FILE_SEP;
		
		List<File> jsps = FileUtils.getFiles(path);
		for (File file : jsps) {
			try {
				String text = FileUtils.readFile(file);
				result.addAll(this.extractKeys(file.getName(), text, nonExist));
			} catch (IOException e) {
				log.error(StackTraceUtils.getStackTrace(e));
			}

		}
		return result;
	}

	private List<I18nDto> extractKeys(String page, String text, Boolean nonExist) {
		List<I18nDto> result = new ArrayList<I18nDto>();

		String pattern = "(titleKey|key).?=.?\"(.*?)\"";

		// Create a Pattern object
		Pattern r = Pattern.compile(pattern);

		// Now create matcher object.
		Matcher m = r.matcher(text);
		while (m.find()) {
//			System.out.println("Found: " + m.group(1) + " " + m.group(2));
			
			I18nDto dto = new I18nDto();
			dto.setKey(m.group(2));
			dto.setPage(page);
			I18n i18n = getI18n(dto.getKey());
			if(i18n != null){
				dto.setExist(true);
				dto.setEn(i18n.getEn());
				dto.setEs(i18n.getEs());
				dto.setId(i18n.getId());
			}
			if(nonExist){
				if(i18n == null) {					
					result.add(dto);
				}
			} else {				
				result.add(dto);
			}
		}
		return result;
	}

}
